<template>
  <el-dialog
    :title="addForm.id > 0 ? '编辑用户' : '添加用户'"
    v-model="dialogVisble"
    width="35%"
    :before-close="closeBox"
  >
    <div>
      <el-form
        ref="formRef"
        style="max-width: 500px"
        :model="addForm"
        :rules="roleRules"
        label-width="auto"
        class="demo-dynamic"
      >
        <el-form-item prop="cate_id" :label="'用户组'">
          <el-select
            v-model="addForm.cate_id"
            placeholder="选择用户分组"
            clearable
            size="large"
            style="width: 240px; margin-right: 10px"
          >
            <el-option
              v-for="item in cateArr"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item prop="pid" :label="'归属'">
          <el-select
            v-model="addForm.pid"
            placeholder="选择管理员"
            clearable
            size="large"
            style="width: 240px; margin-right: 10px"
          >
            <el-option
              v-for="item in adminArr"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>


        <el-form-item prop="nickname" label="昵称">
          <el-input v-model="addForm.nickname" />
        </el-form-item>

        <el-form-item label="头像">
          <div class="up-img-box">
          <el-image style="width: 100px; height: 100px" :src="addForm.avatar" fit="cover" :preview-src-list="[addForm.avatar]" />
          <div class="up-btn-box" @click="uploadImage">
           <input v-show="false" type="file" ref="fileInput" accept="image/*" @change="handleFileUpload" />
            <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
          </div>  
          </div>
        </el-form-item>


        <el-form-item label="注销" prop="cancel" v-if="addForm.id > 0">
          <el-switch v-model="addForm.cancel" active-text="正常" inactive-text="注销" />
        </el-form-item>

        <el-form-item label="状态" prop="state" v-if="addForm.id > 0">
          <el-switch v-model="addForm.state" active-text="启用" inactive-text="禁用" />
        </el-form-item>

      </el-form>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeBox">取 消</el-button>
        <el-button type="primary" @click="submitForm(formRef)">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, computed, reactive,getCurrentInstance, nextTick } from "vue";
import { ElMessage, FormInstance } from "element-plus";

const currentInstance = getCurrentInstance(); //获取main.js中挂载的实例
const { $api } = currentInstance.appContext.config.globalProperties;

const pors = defineProps({
  showdialog: {
    type: Boolean,
    default: false,
  },
  list: {
    type: Object,
    default: {
      id: 0,
      nickname: "", // 
      cate_id: "", // 
      state: "", //
      cancel: "", //
      avatar:'',
      pid:0
    },
  },
  cateArr: {
    type: Array,
    default: [{ name: "请选择用户组", id: 0 }],
  },
  adminArr: {
    type: Array,
    default: [{ name: "请选择管理员", id: 0 }],
  },
});
const formRef = ref<FormInstance>(); //定义form
//表单提交元素
const addForm = computed(() => pors.list);

const fileInput = ref(null); //上传控件

//表单元素的规则
const roleRules = reactive({
  nickname: [
    {
      required: true,
      message: "请输入昵称",
      trigger: "blur", //验证逻辑的触发方式
    },
  ],
  cate_id: [
    {
      required: true,
      message: "请选择分组",
      trigger: "blur", //验证逻辑的触发方式
    },
  ],
});

const emits = defineEmits(["useConfirm", "useClose"]); //定义一个或多个自定义按钮事件 传递到父组件

const dialogVisble = ref(false); // 定义控制弹窗显隐的变量

//关闭模态框
const closeBox = () => {
  if (!formRef) return;
  formRef.value.resetFields();
  dialogVisble.value = false; //重置为空
  emits("useClose", dialogVisble.value);
};

//确定/提交
const submitForm = (formData: FormInstance | undefined) => {
  if (!formData) return;
  //校验
  formData.validate((valid) => {
    if (valid) {
      // console.log();

      dialogVisble.value = false;
      emits("useConfirm", addForm.value);
      formData.resetFields(); //重置为空
    } else {
      console.log("error submit!");
      return false;
    }
  });
};

//图片上传
const uploadImage =  () => {
  fileInput.value.click();
};
//input 点击事件
const handleFileUpload =(event) => {
  console.log(event,"55");
  // file.value = event.target.files[0]; // 上传的内容
  var sizeLenght = event.target.files[0].size; //文件大小
  var size = sizeLenght / (1024 * 1024);
  // state.fileSize = size.toFixed(2); //文件大小 四舍五入保留小数后两位
  // state.fileName = event.target.files[0].name; // 文件名称
  // state.isUpLoad = true;

  // var maxlenght = 1020*1020*5; //未登录则最大5M
  // if (state.isLogin) {
  //   maxlenght = 1020*1020*20; //登录则最大20M
  // }
  // //大于100M时返回
  // if (sizeLenght > maxlenght) {
  //   // console.log("文件太大",state.fileSize/(1024*1024));
  //   msg({ type: "warn", text: "文件太大" });
  //   state.isUpLoad = false;
  //   return false;
  // }
   upFileService(event); //上传到服务器
//   console.log(event.target.files[0]);
};

//提交到服务器
const upFileService = (event) => {
  const formdata = new FormData();
  formdata.append("file",event.target.files[0]); //转为文件流
  formdata.append("name", event.target.files[0].name); //文件名称参数
  formdata.append("folder","user_head")
    $api.post("v1/login/use/up_image", formdata).then((res) => {
      if(res.code == 200){
        addForm.value.avatar = res.data.img;
      }
  });

};

// 将变量暴露出来
defineExpose({
  dialogVisble
});
</script>
<style>
.up-img-box{
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}
.up-btn-box{
  width: 100px;
  height: 100px;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  border: 1px solid #DDD;
  margin-left: 30px;
}
</style>
